# talents_tab.py
import tkinter as tk
from tkinter import messagebox
from talent import * 
import platform


class SwitchTalentCirle():
    def __init__(self, talent_pad, x, y, radius, img_save_dir, callback = None):
        self.x = x
        self.y = y
        self.radius = radius
        self.talent_pad = talent_pad
        self.image_id = None
        self.name = None
        self.data = None
        self.small_talent = None
        self.core_talent = None
        self.img_save_dir = img_save_dir
        self.callback = callback
        self.circle_id = self.talent_pad.create_oval(
           self.x - self.radius, self.y - self.radius,  self.x + self.radius, self.y + self.radius,
           fill="lightblue", outline="white", width=2
        )
        self.geted_point = 0
        self.small_talent_info_map = None
    
    def set_callback(self, callback):
        self.callback = callback

    def SetTalent(self, name, data):
        self.ResetTalent()
        print(self, 'SetTalent', name)
        self.name = name
        self.data = data
        
        if self.image_id is not None:
            self.talent_pad.delete(self.image_id)
        # 使用Pillow加载WebP图片
        url = os.path.join(self.img_save_dir, data['img_url'].split('/')[-1])

        image = Image.open(url)  # 使用Pillow打开WebP图片

        # 计算目标图片大小（例如，圆的直径）
        target_size = int(2 * self.radius)
        
        # 缩放图片到目标大小
        image = image.resize((target_size, target_size), Image.Resampling.LANCZOS)

        self.image = ImageTk.PhotoImage(image)  # 转换为tkinter可用的格式
        
        # # 在圆圈中心添加图片
        self.image_id = self.talent_pad.create_image(self.x, self.y, image=self.image)
        self.talent_pad.tag_bind(self.image_id, "<Button-1>", lambda event: self.callback())
    
    def on_resize(self, event):
        if(self.small_talent):
            self.small_talent.on_resize(event)
        if(self.core_talent):
            self.core_talent.on_resize(event)

    def ResetTalent(self):
        print(self, 'ResetTalent')
        self.name = None
        self.data = None
        self.geted_point = 0
        self.small_talent_info_map = None
        if self.image_id is not None:
            self.talent_pad.delete(self.image_id)
            self.image_id = None
    def IsSelected(self):
        return self.name != None
    
    def Name(self):
        return self.name

    def DrawSmallTalent(self, talent_pad, event, width, height):
        data = self.data['small_talents_map']
        self.small_talent = SmallTalent(self.name, data, talent_pad, self.img_save_dir, width, height)
        self.small_talent.draw()
        self.small_talent.on_resize(event)
        if(self.small_talent_info_map is not None):
            self.small_talent.SetTalentInfo(self.small_talent_info_map)
        self.small_talent.update_bright_by_total(self.geted_point)
    
    def DrawCoreTalent(self, core_talent_pad, event, width, height):
        data = self.data['core_talents_map']
        self.core_talent = CoreTalent(self.name, data, core_talent_pad, self.img_save_dir, width, height)
        self.core_talent.draw()
        self.core_talent.on_resize(event)

    def level_up_small_talent(self, id):
        print('level_up_small_talent', id)
        if(self.small_talent):
            if(self.small_talent.level_up(id, self.geted_point)):
                self.geted_point += 1
                self.small_talent_info_map = self.small_talent.talent_info_map
            self.small_talent.update_bright_by_total(self.geted_point)

    def level_down_small_talent(self, id):
        print('level_down_small_talent', id)
        if(self.geted_point <= 0):
            return
        if(self.small_talent):
            if(self.small_talent.level_down(id, self.geted_point)):
                self.geted_point -= 1
                self.small_talent_info_map = self.small_talent.talent_info_map
            self.small_talent.update_bright_by_total(self.geted_point)

    def IsClear(self):
        if(self.IsSelected()):
            print(self.name, 'IsClear', self.geted_point)
            return self.geted_point == 0
        return True

class DrawTalent():
    def __init__(self, parent, talent_data, img_save_dir):
        self.max_point = 90
        # Define a <<RightClick>> virtual event that works cross-platform
        if platform.system() == "Darwin":
            parent.event_add("<<RightClick>>", "<Button-2>")
        else:
            parent.event_add("<<RightClick>>", "<Button-3>")

        self.width = 1000
        self.height = 500
        self.data = talent_data.talent_data
        self.talent_group_map = talent_data.talent_group_map
        # 创建左侧画布
        self.left_talent_pad = tk.Canvas(parent, width = 100, height = self.height + 100, bg="black")
        self.left_talent_pad.pack(side="left", padx=10, pady=10, anchor="w")

        # 创建一个 Frame 容器，用于水平排列
        frame = tk.Frame(parent)
        frame.pack(side="top", padx=20, pady=20, anchor="n")

        # 创建 info_pad 画布
        self.info_pad = tk.Canvas(frame, width=100, height=20, bg="white")
        self.info_pad.pack(side="right", padx=10)  # 向左显示

        self.total_text_id = None

        # 创建 core_talent_pad 画布
        self.core_talent_pad = tk.Canvas(frame, width=self.width, height=100, bg="black")
        self.core_talent_pad.pack(side="left", padx=10)  # 向左显示

        # 创建talent_pad
        self.talent_pad = tk.Canvas(parent, width = self.width, height = self.height, bg="black")  # 画布大小和背景色
        self.talent_pad.pack(side="top", padx=20, pady=20, anchor="n")  # 向顶部靠左显示

        # 创建一个方框
        box_x1, box_y1, box_x2, box_y2 = 50, 50, 200, 100  # 方框的坐标
        self.info_pad.create_rectangle(box_x1, box_y1, box_x2, box_y2, outline="black", width=2, tags="total_points")


        
        self.draw_small_talent = None
        self.draw_core_talent  = None
        
        self.talent_switchs = []
        self.index = None
        # 圆的参数 
        self.circle_positions = [
            (50, 100, 40),  # 圆1的中心坐标
            (50, 250, 40),  # 圆2的中心坐标
            (50, 400, 40)   # 圆3的中心坐标
        ]
        # 绘制圆和绑定事件
        for index, (x, y, radius) in enumerate(self.circle_positions):
            circle = SwitchTalentCirle(self.left_talent_pad, x, y, radius, img_save_dir)
            self.talent_switchs.append(circle)
        # 绑定鼠标点击事件
        self.talent_switchs[0].set_callback(lambda : self.on_basetalent_click())
        self.talent_switchs[1].set_callback(lambda : self.on_secondtalent_click())
        self.talent_switchs[2].set_callback(lambda : self.on_thirdtalent_click())
        self.left_talent_pad.tag_bind(self.talent_switchs[0].circle_id, "<Button-1>", 
                                        lambda  event: self.on_basetalent_click())
        self.left_talent_pad.tag_bind(self.talent_switchs[1].circle_id, "<Button-1>", 
                                        lambda  event: self.on_secondtalent_click())
        self.left_talent_pad.tag_bind(self.talent_switchs[2].circle_id, "<Button-1>", 
                                        lambda  event: self.on_thirdtalent_click())

        # 绑定窗口大小变化事件
        self.talent_pad.bind("<Configure>", self.on_resize)

    def SetTalentTotalPoints(self, max_point):
        self.max_point = max_point

    def bind_talent_circle(self, talent_info_map):
        for id in talent_info_map:
            talent_circle = talent_info_map[id].talent_circle
            print(talent_circle, talent_circle.image_id)
            # 在绑定事件前检查 ID 的有效性
            if talent_circle.image_id and self.talent_pad.find_withtag(talent_circle.image_id):
                self.talent_pad.tag_bind(talent_circle.image_id, "<Button-1>", 
                                            lambda  event, id = id: self.on_smalltalent_left_click(id))
                self.talent_pad.tag_bind(talent_circle.image_id, "<<RightClick>>", 
                                            lambda  event, id = id: self.on_smalltalent_right_click(id))
            else:
                for item_id in self.talent_pad.find_all():
                    tags = self.talent_pad.gettags(item_id)
                    print(f"Item ID: {item_id}, Tags: {tags}")
                print(f"Error: Item {talent_circle.image_id} does not exist.")
                exit(1)
    def draw(self, index):
        self.talent_switchs[index].DrawSmallTalent(self.talent_pad, self.event, self.width, self.height)
        self.talent_switchs[index].DrawCoreTalent(self.core_talent_pad, self.event, self.width, 100)
        self.bind_talent_circle(self.talent_switchs[index].small_talent.talent_info_map)
    def on_smalltalent_left_click(self, id):
        geted_points = [self.talent_switchs[0].geted_point, 
                        self.talent_switchs[1].geted_point, 
                        self.talent_switchs[2].geted_point] 
        if(sum(geted_points) >= self.max_point):
            print('不能再多了')
            return
        if self.index is not None:
            self.talent_switchs[self.index].level_up_small_talent(id)
        self.update_points_text()

    def on_smalltalent_right_click(self, id):
        print('on_smalltalent_right_click', id)
        if self.index is not None:
            if(self.talent_switchs[self.index].geted_point <= 0):
                print('不能再少了')
                return
            self.talent_switchs[self.index].level_down_small_talent(id)
        self.update_points_text()

    def on_resize(self, event):
       self.event = event
       if self.index is not None:
         self.talent_switchs[self.index].on_resize(event)
         if(self.talent_switchs[self.index].small_talent):
             self.bind_talent_circle(self.talent_switchs[self.index].small_talent.talent_info_map)
    
    def on_basetalent_click(self):
        print('on_thirdtalent_click')
        """鼠标点击圆时触发的事件"""
        self.index = 0
        if(not self.talent_switchs[0].IsClear()):
            self.draw(0)
            self.update_points_text()
        elif(self.talent_switchs[1].IsSelected()):
            self.draw(0)
            self.update_points_text()
        else:
            self.SwitchBaseTalent(lambda : self.draw(0))
    def on_secondtalent_click(self):
        print('on_secondtalent_click')
        """鼠标点击圆时触发的事件"""
        self.index = 1
        if(not self.talent_switchs[1].IsClear()):
            self.draw(1)
            self.update_points_text()
        elif(self.talent_switchs[0].IsSelected() and not self.talent_switchs[1].IsSelected()):
            self.SwitchSecondTalent(lambda : self.draw(1))
        elif(self.talent_switchs[1].IsSelected() and not self.talent_switchs[2].IsSelected()):
            self.SwitchSecondTalent(lambda : self.draw(1))
        else:
            self.draw(1)
            self.update_points_text()
    def on_thirdtalent_click(self):
        print('on_thirdtalent_click')
        """鼠标点击圆时触发的事件"""
        self.index = 2
        if(not self.talent_switchs[2].IsClear()):
            self.draw(2)
            self.update_points_text()
        elif(self.talent_switchs[1].IsSelected() and self.talent_switchs[2].IsClear()):
            self.SwitchThirdTalent(lambda : self.draw(2))
        else:
            self.draw(2)
            self.update_points_text()

    def SwitchBaseTalent(self, callback=None):
        """弹出对话框，供用户选择"""
        popup = tk.Toplevel()
        popup.title("选择一个天赋")
        popup.geometry("200x300")

        # 添加一些选择内容
        label = tk.Label(popup, text="请选择一个天赋版块：", font=("Arial", 12))
        label.pack(pady=10)

        # 添加按钮作为选项
        for i in self.talent_group_map:
            btn = tk.Button(popup, text=i, command=lambda i=i: self.SelectOption(popup, i, 0, callback))
            btn.pack(pady=5)

    def SwitchSecondTalent(self, callback = None):
        """弹出对话框，供用户选择"""
        popup = tk.Toplevel()
        popup.title("选择一个天赋")
        popup.geometry("200x300")
        # 添加一些选择内容
        label = tk.Label(popup, text="请选择一个天赋版块：", font=("Arial", 12))
        label.pack(pady=10)
        for i,_,_ in self.talent_group_map[self.talent_switchs[0].Name()]:
            btn = tk.Button(popup, text=i, command=lambda i=i: self.SelectOption(popup, i, 1, callback))
            btn.pack(pady=5)
    
    def SwitchThirdTalent(self, callback = None):
        """弹出对话框，供用户选择"""
        popup = tk.Toplevel()
        popup.title("选择一个天赋")
        popup.geometry("200x300")
        # 添加一些选择内容
        label = tk.Label(popup, text="请选择一个天赋版块：", font=("Arial", 12))
        label.pack(pady=10)

        for base in self.talent_group_map:
            for j,_,_ in self.talent_group_map[base]:
                if(j == self.talent_switchs[1].Name()):
                    continue
                btn = tk.Button(popup, text=j, command=lambda j=j: self.SelectOption(popup, j, 2, callback))
                btn.pack(pady=5)

    def SelectOption(self, popup, option, index, callback):
        """选择一个项目后关闭对话框"""
        self.talent_switchs[index].SetTalent(option, self.data[option]['data'])
        self.update_points_text()
        # 在方框中间显示 total_points
        popup.destroy()
        if(callback is not None):
            callback()

    def update_points_text(self):
       print('update_points_text', self.index, self.talent_switchs[self.index].geted_point)
       if(self.total_text_id != None):
        self.info_pad.delete(self.total_text_id)
       self.total_text_id = self.info_pad.create_text(60,  10, 
                                text=f"已经设置: {self.talent_switchs[self.index].geted_point}", font=("Arial", 12))

class TalentsTab(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        self.talent_group_map = None
        self.talent_circles = None
        self.depence_lines = None
        self.create_widgets()

    def create_widgets(self):
        # 在这里添加天赋标签页的控件和布局
        label = tk.Label(self, text="天赋预览")
        label.pack(pady=10)
        DrawTalent(self, TalentData(), './downloaded_images/')

